package cn.edu.xmut.chen.zhlg.zhlg.message.mapper;


import cn.edu.xmut.chen.zhlg.zhlg.message.entity.PrivateMessage;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface PrivateMessageMapper extends BaseMapper<PrivateMessage> {
    @Insert("INSERT INTO tb_message(id, chat_id, sender_id, receiver_id, content_type, content, create_time) " +
            "VALUES(#{id}, #{chatId}, #{senderId}, #{receiverId}, #{contentType}, #{content}, #{createTime})")
    int insert(PrivateMessage message);

    @Select("SELECT * FROM tb_message " +
            "WHERE chat_id = #{chatId} " +
            "ORDER BY create_time " +
            "DESC LIMIT #{offset}, #{size}")
    List<PrivateMessage> selectByChatId(@Param("chatId") String chatId,
                                      @Param("offset") int offset,
                                      @Param("size") int size);



    @Select("SELECT * FROM tb_message " +
            "WHERE chat_id = #{chatId} " +
            "ORDER BY create_time " +
            "DESC LIMIT 1")
    PrivateMessage selectById(@Param("chatId") String chatId);



    @Update("UPDATE tb_message SET " +
            "deleted_by_sender = CASE WHEN sender_id = #{userId} THEN 1 ELSE deleted_by_sender END, " +
            "deleted_by_receiver = CASE WHEN receiver_id = #{userId} THEN 1 ELSE deleted_by_receiver END " +
            "WHERE chat_id = #{chatId}")
    int markDeletedByUser(@Param("chatId") String chatId, @Param("userId") String userId);



    @Select("SELECT * FROM tb_message WHERE chat_id = #{chatId} " +
            "AND ((sender_id = #{userId} AND deleted_by_sender = 0) " +
            "OR (receiver_id = #{userId} AND deleted_by_receiver = 0)) " +
            "ORDER BY create_time Desc LIMIT #{offset}, #{size}")
    List<PrivateMessage> selectVisibleByChatId(@Param("chatId") String chatId,
                                               @Param("userId") String userId,
                                               @Param("offset") int offset,
                                               @Param("size") int size);


}